public class P_C_problem_v1 {
    public static void main(String[] args) {
        Reso r = new Reso();
        new Thread(new Prod(r)).start();
        new Thread(new Cums(r)).start();
    }
}
class Reso {
     boolean empty = true;  //设置状态符，表示缓存区为空
     int id;
    public synchronized void produce(int i ) throws InterruptedException {
        while(true){
            if(!empty){         //当缓存区为非空时，生产者不生产
               this.wait();
            }
            id=i++;
            this.notifyAll();
            System.out.println("Producer has produced resource : " + id);
            empty = false;

        }
    }

    public synchronized void consume() throws InterruptedException {
        while(true){
            if(empty){    //当缓存区为空时，消费者进程等待
                this.wait();
            }
            this.notifyAll();
            System.out.println("Consumer has consumed resource : " + id);
            empty = false;

        }
    }


}



class Prod implements  Runnable{
    private Reso resource ;
    public  Prod(){}
    public Prod(Reso resource){
        this.resource = resource;
    }
    @Override
    public void  run() {
        for (int i = 0; i < 1000; i++) {
            try {
                resource.produce(i);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

class Cums implements Runnable{
    private Reso resource ;
    public  Cums(){}
    public Cums(Reso resource){
        this.resource = resource;
    }

    @Override
    public void run() {
        for (int i = 0; i < 1000; i++) {
            try {
                resource.consume();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}